package logic

import (
	"context"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentQualificationsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentQualificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentQualificationsLogic {
	return AgentQualificationsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentQualificationsLogic) AgentQualifications(req *types.AgentQualificationsReq) error {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: uid})
	if err != nil {
		return err
	}

	switch req.Type {
	case 1, 2:
		if len(req.RealName) < 2 {
			return errorx.NewDefaultError("姓名有误，请重新输入。")
		}
		if len(req.IdCard) != 18 {
			return errorx.NewDefaultError("身份证有误，请重新输入。")
		}
		_, err := l.svcCtx.AgentRpc.AgentByIdCard(l.ctx, &agentClient.AgentByIdCardReq{IdCard: req.IdCard})
		if err == nil {
			return errorx.NewCodeReason(errorx.AlreadyExistsCode, "身份证已被认证")
		}
		agentParam.RealName = req.RealName
		agentParam.IdCard = req.IdCard
	default:
		return errorx.NewDefaultError("输入有误，请重试刷新再试。")
	}

	agentParam.Type = req.Type
	agentParam.Status = 1
	agentParam.UpdateTime = time.Now().Unix()
	_, err = l.svcCtx.AgentRpc.AgentUpdate(l.ctx, agentParam)
	if err != nil {
		return err
	}
	return nil
}
